var mongoose = require('mongoose');
var multer =require('multer');
var path =require('path');
const DataModel = require('../Models/upload.model');



//上传
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, './uploads')
    },
    //下面文件命名方式，加时间戳加文件原始后缀
    filename: function (req, file, cb) {
      cb(null, file.fieldname + '-' + Date.now()+path.extname(file.originalname))
    }
  })

exports.upload = function(req,res,next){
	var typeId = req.params.typeId;	
    var upload = multer({ 
        storage: storage 
    }).single('avatar');
    
    upload(req,res,function(err){
		req.file.typeId = typeId
        const dataModel = new DataModel(req.file);        
            dataModel.save()
            .then(data=>{
                res.json(data);
            })
        res.end('The file is uploaded')
    })
}

//创建
exports.create = function (req, res, next) {
	const dataModel = new DataModel(req.body);
	dataModel.save()
		.then(data => {
			res.json(data);
		})
}
//获取
exports.get = function(req,res,next){
	var id = req.params.id;

	DataModel.findById(id, function (err, data) {
	  res.json(data);
	})
}

//更新操作
exports.update = function(req,res,next){
	const id = req.params.id;
	
	DataModel.findByIdAndUpdate(id, {$set: req.body}, {new:false})//找到就更新，没找到就新增
	.then(data=>{
		res.json(data);//返回修改前的数据
	})

}
//删除
exports.remove = function(req,res,next){
	const id = req.params.id;

	DataModel.findByIdAndRemove(id,function(err,data){
		res.json(data);
	})
	
}
//获取列表记录
exports.classifyLists = function (req, res, next) {
    var ids = req.body.typeId.split(",");
    if (ids.length > 0) {
        DataModel.find({typeId: {$in: ids}}).then(data=> {
                res.json(data);
            })
    } else {
        res.json({"msg": "请求失败", "status": 404})
    }
}

//列表
exports.list=function(req,res,next){
	var page=(req.body.page)?req.body.page:1;
	var limit=(req.body.limit)?req.body.limit:10;
	//定义查询条件
	var queryCondition={ };
	if(req.body.filename&&req.body.filename.trim().length>0){
		 filename=req.body.filename;
		queryCondition={
			'filename':new RegExp(filename,'i')
		}
	}
	if(req.body.typeId && req.body.typeId.trim().length>0){
		typeId = req.body.typeId;
		// Object.assign对象合并
		queryCondition = Object.assign(queryCondition,
			{
				typeId: typeId
			}
		)
	}
	
	DataModel.paginate(queryCondition,{sort:{_id:-1}, page:parseInt(page),limit:parseInt(limit)},
	function(err,result){
		result.rows=result.docs;
		delete result.docs;
		res.json(result)
	});
}
//多个删除
exports.deletes = function (req, res, next) {
	const ids = req.body.ids;
	if (ids.length > 0) {
		DataModel.remove({ _id: { $in: ids.split(',') } })
			.then(data => {
				res.json({ "msg": "deletes success", "status": 200 });
			})
	} else {
		res.json({ "msg": "deletes fail", "status": 404 });
	}
}